package com.baidu.health.service;

import com.alibaba.fastjson.JSON;
import com.baidu.health.pojo.TbArticle;
import com.baidu.health.pojo.resultVo.resultVo;
import com.baidu.health.pojo.resultVo.userMagess;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baidu.health.pojo.TbUser;
import com.baidu.health.mapper.TbUserMapper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>{

    @Autowired
    TbUserMapper userMapper;

    @Autowired
    RestHighLevelClient restHighLevelClient;


    public userMagess getUserMessage(Integer userId)throws Exception {
        TbUser user = userMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserId, userId));

        SearchRequest request = new SearchRequest("health");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("userId",userId)).must(QueryBuilders.termQuery("delFlag",0)).must(QueryBuilders.termQuery("checkFlag",0));

        request.source(builder.query(boolQueryBuilder));

        SearchHit[] hits = restHighLevelClient.search(request, RequestOptions.DEFAULT).getHits().getHits();

        List<TbArticle> list = new ArrayList<>();

        for (SearchHit hit : hits) {
            TbArticle tbArticle = JSON.parseObject(hit.getSourceAsString(), TbArticle.class);
            list.add(tbArticle);
        }
        return new userMagess(200,"查询成功",user,list);
    }
}




